package org.ww.ware.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.ww.common.constant.WareConstant;
import org.ww.common.to.SkuInfoTo;
import org.ww.common.utils.PageUtils;
import org.ww.common.utils.Query;
import org.ww.common.utils.R;
import org.ww.ware.dao.PurchaseDao;
import org.ww.ware.entity.PurchaseDetailEntity;
import org.ww.ware.entity.PurchaseEntity;
import org.ww.ware.entity.WareSkuEntity;
import org.ww.ware.feign.ProductFeignService;
import org.ww.ware.service.PurchaseDetailService;
import org.ww.ware.service.PurchaseService;
import org.ww.ware.service.WareSkuService;
import org.ww.ware.vo.MergeVo;
import org.ww.ware.vo.PurchaseDoneItemVo;
import org.ww.ware.vo.PurchaseDoneVo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;
    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByParams(Map<String, Object> params) {
        LambdaQueryWrapper<PurchaseEntity> wrapper = Wrappers.lambdaQuery();
        String key = (String) params.get("key");
        if(StringUtils.isNotBlank(key)){
            wrapper.eq(PurchaseEntity::getId,key);
        }
        String status = (String) params.get("status");
        if(StringUtils.isNotBlank(status)){
            wrapper.eq(PurchaseEntity::getStatus,status);
        }
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByUnreceivePurchase(Map<String, Object> params) {
        LambdaQueryWrapper<PurchaseEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(PurchaseEntity::getStatus, WareConstant.PurchaseFormEnum.NEW.getCode()).or().eq(PurchaseEntity::getStatus,WareConstant.PurchaseFormEnum.ASSIGN.getCode());
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void merge(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        //采购单为空就自动创建
        if (null == purchaseId){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseFormEnum.NEW.getCode());
            save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //确定采购单的状态是0或1才能够进行采购
        PurchaseEntity purchaseEntity = this.getById(purchaseId);
        if(ObjectUtils.isNotEmpty(purchaseEntity) &&
                (purchaseEntity.getStatus().equals(WareConstant.PurchaseFormEnum.NEW.getCode()) ||
                        purchaseEntity.getStatus().equals(WareConstant.PurchaseFormEnum.ASSIGN.getCode()))){
            //合并采购单：更改采购需求的采购id
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> purchaseDetailEntities = Optional.ofNullable(mergeVo.getItems())
                    .orElseGet(ArrayList::new)
                    .stream()
                    .map(m -> {
                        PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                        detailEntity.setPurchaseId(finalPurchaseId);
                        detailEntity.setStatus(WareConstant.PurchaseDemandFormEnum.ASSIGN.getCode());
                        detailEntity.setId(m);
                        return detailEntity;
                    }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(purchaseDetailEntities);
        }




    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void received(List<Long> ids) {
        //1、确定采购单的状态是新建或者已分配
        List<PurchaseEntity> purchaseEntities = baseMapper.selectBatchIds(ids);
        List<PurchaseEntity> updatePurchases = Optional.ofNullable(purchaseEntities)
                .orElseGet(ArrayList::new)
                .stream()
                .filter(p -> p.getStatus().equals(WareConstant.PurchaseFormEnum.NEW.getCode()) ||
                        p.getStatus().equals(WareConstant.PurchaseFormEnum.ASSIGN.getCode()))
                .map(p -> {
                    //2、更改采购单的状态
                    p.setStatus(WareConstant.PurchaseFormEnum.RECEIVE.getCode());
                    return p;
                }).collect(Collectors.toList());

        this.updateBatchById(updatePurchases);

        //3、更改采购项的状态
        Integer purchaseCode = WareConstant.PurchaseDemandFormEnum.PURCHASE.getCode();
        purchaseDetailService.updateStatusByPurhcaseIds(ids,purchaseCode);

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void purchaseDone(PurchaseDoneVo purchaseDoneVo) {
        List<PurchaseDoneItemVo> items = purchaseDoneVo.getItems();
        boolean flag = true;
        List<WareSkuEntity> wareSkuEntities = new ArrayList<>();

        //获取所有采购项信息
        List<Long> purchaseItemIds = Optional.ofNullable(items)
                .orElseGet(ArrayList::new)
                .stream()
                .map(PurchaseDoneItemVo::getItemId)
                .distinct()
                .collect(Collectors.toList());
        List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.getByIds(purchaseItemIds);

        //获取所有skuId
        List<Long> skuIds = Optional.ofNullable(purchaseDetailEntities)
                .orElseGet(ArrayList::new)
                .stream()
                .map(PurchaseDetailEntity::getSkuId)
                .distinct()
                .collect(Collectors.toList());
        //调用远程服务查询sku信息
        R productR = productFeignService.getBySkuIds(skuIds);
        List<SkuInfoTo> data = JSON.parseArray(JSON.toJSONString(productR.get("data")), SkuInfoTo.class);

        Map<Long, PurchaseDetailEntity> purchaseDetailEntityMap = Optional.ofNullable(purchaseDetailEntities)
                .orElseGet(ArrayList::new)
                .stream()
                .collect(Collectors.toMap(PurchaseDetailEntity::getId, item -> item));

        //1、更改采购项状态
        List<PurchaseDetailEntity> updatePurchaseDetails = new ArrayList<>();

        for (PurchaseDoneItemVo item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item.getItemId());
            if(item.getStatus().equals(WareConstant.PurchaseDemandFormEnum.ERROR.getCode())){
                flag = false;
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDemandFormEnum.ERROR.getCode());
            }else{
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDemandFormEnum.FINISH.getCode());
                //3、商品入库存
                //构造入库存list
                PurchaseDetailEntity detailEntity = purchaseDetailEntityMap.get(item.getItemId());
                WareSkuEntity wareSkuEntity = new WareSkuEntity();
                wareSkuEntity.setSkuId(detailEntity.getSkuId());
                wareSkuEntity.setWareId(detailEntity.getWareId());
                wareSkuEntity.setStock(detailEntity.getSkuNum());
                wareSkuEntity.setStockLocked(0);
                Optional.ofNullable(data)
                        .orElseGet(ArrayList::new)
                        .stream()
                        .filter(d -> d.getSkuId().equals(detailEntity.getSkuId()))
                        .findFirst()
                        .ifPresent(d -> wareSkuEntity.setSkuName(d.getSkuName()));
                wareSkuEntities.add(wareSkuEntity);
            }

            updatePurchaseDetails.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(updatePurchaseDetails);

        //2、更改采购单状态：采购项状态都是完成则该状态完成，否则异常
        PurchaseEntity updatePurchase = new PurchaseEntity();
        updatePurchase.setId(purchaseDoneVo.getId());
        updatePurchase.setStatus(flag ? WareConstant.PurchaseFormEnum.FINISH.getCode() : WareConstant.PurchaseFormEnum.ERROR.getCode());
        baseMapper.updateById(updatePurchase);

        //更改商品库存
        wareSkuService.purchaseUpdate(wareSkuEntities);

    }


}